import React, { useState, useEffect } from 'react'
import cityData from "../../cityData"
import { useMappedState, useDispatch } from "redux-react-hook"
import {
    Form,
    Input,
    Button,
    Select,
    Table,
    Space,
    message,
    Drawer,
    Popconfirm,
    Switch,
    Modal,
    Descriptions,
} from 'antd';
import request from "../../../utils/request";
import Home from "../../../store/actions/Home";
import Brokers from "../../../store/actions/Broker";


import "./House.css"
const HouseRent = () => {
    const { Option } = Select;
    const [city, setCity] = useState([]);
    const [county, setCounty] = useState([]);
    const [flag, setFlag] = useState("新增");
    const [visible, setvisible] = useState(false);

    const dispatch = useDispatch();
    const { Homelist, from } = useMappedState((state) => {
        return state.Home
    })
    const { Brokerlist } = useMappedState((state) => {
        return state.Broker
    })
    useEffect(() => {
        getter();
    }, []);

    //获取数据
    const getter = async () => {
        const res = await request({
            url: "/api/Gethome",
            method: "get",
        })
        const action = Home.getHome(res.data);
        dispatch(action);
        const newress = request({
            url: "/api/Getbroker",
            method: "get",
            params: {
                ...{ state: "在职" }
            }
        })
        newress.then(res => {
            if (res.code !== 200) {
                message.error(res.message);
            }
            dispatch(Brokers.getBroker(res.data))
        })
    }

    //搜索
    const onFinish = async (values) => {
        let res = await request({
            url: '/api/searchHome',
            method: "get",
            params: {
                ...values,
            }
        })
        const action = Home.searchHome(res.data);
        dispatch(action);
    }
    //城市
    const City = (changedValues) => {
        if (changedValues.province) {
            setCity([]);
            setCounty([]);
            const cityList = cityData.filter(item => {
                if (item.name === changedValues.province) {
                    return { ...item }
                }
            })
            const newcity = { ...cityList };
            setCity([...newcity[0].cityList]);
        } else if (changedValues.city) {
            setCounty([]);
            const countyList = city.filter(item => {
                if (item.name === changedValues.city) {
                    return { ...item }
                }
            })
            const newcounty = { ...countyList };
            setCounty([...newcounty[0].areaList])
        }
    }


    //表格
    const columns = [
        {
            title: '序号',
            dataIndex: 'key',
            key: 'key',
            render: text => <a>{text}</a>,
        },
        {
            title: '楼盘名称',
            dataIndex: 'name',
            key: 'name',
        },
        {
            title: '详细地址',
            dataIndex: 'site',
            key: 'site',
        },
        {
            title: '价格/㎡',
            dataIndex: 'rent',
            key: 'rent',
        },
        {
            title: '排序',
            dataIndex: 'id',
            key: 'id',
        },
        {
            title: '更新时间',
            dataIndex: 'date',
            key: 'date',
        },
        {
            title: '状态',
            key: 'state',
            render: (text, record) => (
                <Space size="middle">
                    <Switch checkedChildren="开启" unCheckedChildren="关闭" checked={text.state} onClick={() => State(record)} />
                </Space>
            ),
        },
        {
            title: '经纪人',
            dataIndex: 'broker',
            key: 'broker',
        },
        {
            title: '操作',
            key: 'action',
            render: (text, record) => (
                <Space size="middle">
                    <a onClick={() => showModal(record)}>详情</a>
                    <a onClick={() => AddEditor("编辑", record)}>编辑</a>
                    <Popconfirm
                        title="是否要删除？请再次确定"
                        onConfirm={() => Delete(record)}
                        okText="Yes"
                        cancelText="No"
                    >
                        <a>删除</a>
                    </Popconfirm>
                    <a onClick={() => AddEditor("经纪人", record)}>指派经纪人</a>
                </Space>
            )
        },
    ];
    //删除
    const Delete = async (text) => {
        const res = await request({
            url: "/api/Deletehome",
            method: "delete",
            params: { id: text.id },
        })
        message.success(res.message);
        getter();
    }
    //新增或者编辑
    const AddEditor = (setflag, text) => {
        if (setflag === "新增") {
            setFlag(setflag)
            showDrawer()
        } else if (setflag === "经纪人") {
            setFlag("编辑");
            setisBroker(true);
            dispatch(Home.editor(text))
        } else {
            setFlag(setflag);
            dispatch(Home.editor(text))
            showDrawer();
        }
    }

    //受控组件
    const transform = (type, e) => {
        dispatch(Home.editor({ type, e }))
    }

    //开启弹框
    const showDrawer = () => {
        setvisible(true);
    };

    //关闭弹框
    const onClose = () => {
        setisBroker(false);
        setvisible(false);
        dispatch(Home.editor({}))
    };

    //新增或者修改 调用接口
    const Finish = () => {
        if (flag === "新增") {
            const action = Home.addHome();
            dispatch(action);
        } else {
            const action = Home.editorHome();
            dispatch(action);
        }
        getter();
        onClose();
    };

    //状态
    const State = async (text) => {
        let res = await request({
            url: "/api/stateHome",
            method: "put",
            data: {
                id: text.id
            }
        })
        message.success(res.message);
        getter();
    }

    //详情
    const [isModalVisible, setIsModalVisible] = useState(false);
    const [detial, setdetial] = useState({
        name: "",
        province: "",
        site: "",
        price: "",
        rent: "",
        broker: "",
        home: "",
    });

    const showModal = (text) => {
        setdetial({
            ...text
        })
        setIsModalVisible(true);
    };

    const handleOk = () => {
        setIsModalVisible(false);
    };

    const handleCancel = () => {
        setIsModalVisible(false);
    };


    //经纪人
    const CancelBroker = () => {
    };

    const [isBroker, setisBroker] = useState(false);

    return (
        <div className="HouseRent">
            <div className="HouseTop">
                <Form name="complex-form" onFinish={onFinish} onValuesChange={City}>
                    <Form.Item>
                        <Input.Group compact>
                            <Form.Item
                                name="province"
                                noStyle
                            >
                                <Select placeholder="请选择省份" style={{ width: '100%' }}>
                                    {
                                        cityData.length && cityData.map((item, index) => {
                                            return <Option value={item.name} key={index}>{item.name}</Option>
                                        })
                                    }
                                </Select>
                            </Form.Item>
                        </Input.Group>
                    </Form.Item>
                    <Form.Item>
                        <Input.Group compact>
                            <Form.Item
                                name="city"
                                noStyle
                            >
                                <Select placeholder="请选择城市" style={{ width: '100%' }}>
                                    {
                                        city.length && city.map((item, index) => {
                                            return <Option value={item.name} key={index}>{item.name}</Option>
                                        })
                                    }
                                </Select>
                            </Form.Item>
                        </Input.Group>
                    </Form.Item>
                    <Form.Item>
                        <Input.Group compact>
                            <Form.Item
                                name="county"
                                noStyle
                            >
                                <Select placeholder="请选择区县" style={{ width: '100%' }}>
                                    {
                                        county.length && county.map((item, index) => {
                                            return <Option value={item} key={index}>{item}</Option>
                                        })
                                    }
                                </Select>
                            </Form.Item>
                        </Input.Group>
                    </Form.Item>
                    <Form.Item
                        name="word"
                    >
                        <Input placeholder="请输入关键字" />
                    </Form.Item>
                    <Form.Item label=" " colon={false}>
                        <Button type="primary" htmlType="submit">
                            搜索
                        </Button>
                    </Form.Item>
                </Form>
            </div>
            <div className="Housemain">
                <div className="housetop">
                    <Button type="primary" onClick={() => AddEditor("新增")}>新增</Button>
                </div>
                <div className="housemain">
                    <Table columns={columns} dataSource={Homelist} />
                </div>
            </div>
            <div className="model">
                <Drawer
                    title={flag}
                    width={300}
                    onClose={() => onClose()}
                    visible={visible}
                    bodyStyle={{ paddingBottom: 80 }}
                >
                    <Space direction="vertical">
                        <Input placeholder="请输入楼盘名称" value={from.name} onChange={(e) => transform("name", e.target.value)} />
                        <Select placeholder="请选择省份" value={from.province} style={{ width: '100%' }} onChange={(e) => { City({ province: e }); transform("province", e) }}>
                            {
                                cityData.length && cityData.map((item, index) => {
                                    return <Option value={item.name} key={index}>{item.name}</Option>
                                })
                            }
                        </Select>
                        <Select placeholder="请选择城市" value={from.city} style={{ width: '100%' }} onChange={(e) => { City({ city: e }); transform("city", e) }}>
                            {
                                city.length && city.map((item, index) => {
                                    return <Option value={item.name} key={index}>{item.name}</Option>
                                })
                            }
                        </Select>
                        <Select placeholder="请选择区县" value={from.county} style={{ width: '100%' }} onChange={(e) => { City({ county: e }); transform("county", e) }}>
                            {
                                county.length && county.map((item, index) => {
                                    return <Option value={item} key={index}>{item}</Option>
                                })
                            }
                        </Select>
                        <Input placeholder="请输入关键字" value={from.word} onChange={(e) => transform("word", e.target.value)} />
                        <Input placeholder="请输入价格" value={from.price} onChange={(e) => transform("price", e.target.value)} />
                        <Input placeholder="请输入租金" value={from.rent} onChange={(e) => transform("rent", e.target.value)} />
                        <Select
                            placeholder="请选择类型"
                            value={from.home}
                            style={{ width: '100%' }}
                            onChange={(e) => { transform("home", e) }}
                        >
                            <Option value="新房">新房</Option>
                            <Option value="二手房">二手房</Option>
                            <Option value="租房">租房</Option>
                        </Select>
                        <Button type="primary" onClick={() => Finish()}>提交</Button>
                    </Space>
                </Drawer>
            </div>
            <div className="detial">
                <Modal title="详情" visible={isModalVisible} onOk={handleOk} onCancel={handleCancel}>
                    <Descriptions title={detial.name}>
                        <Descriptions.Item label="省份">{detial.province}</Descriptions.Item>
                        <Descriptions.Item label="价格">{detial.price}/m2</Descriptions.Item>
                        <Descriptions.Item label="租金">{detial.rent}/月</Descriptions.Item>
                        <Descriptions.Item label="经纪人">{detial.broker}</Descriptions.Item>
                        <Descriptions.Item label="类型">{detial.home}</Descriptions.Item>
                        <Descriptions.Item label="详细地址">
                            {detial.site}
                        </Descriptions.Item>
                    </Descriptions>
                </Modal>
            </div>
            <div className="broker">
                <Drawer
                    title="经纪人"
                    width={300}
                    visible={isBroker}
                    onClose={() => onClose()}
                    bodyStyle={{ paddingBottom: 80 }}
                >
                    <Space direction="vertical">
                        <Select
                            placeholder="请选择经纪人"
                            value={from.broker}
                            style={{ width: '100%' }}
                            value={from.broker}
                            onChange={(e) => transform("broker", e)}
                        >
                            {
                                Brokerlist.length && Brokerlist.map((item, index) => {
                                    return <Option value={item.name} key={index}>{item.name}</Option>
                                })
                            }
                        </Select>
                        <Button type="primary" onClick={() => Finish()}>提交</Button>
                    </Space>
                </Drawer>
            </div>
        </div >
    )
}

export default HouseRent
